<?php
/* phpYahoo Class 1.5.0
 * Written by Jay Denis (jay@gotfoo.org)
 * Google Project Page: http://code.google.com/p/phpyahoo/
 * Released under GNU Lesser General Public License (http://www.gnu.org/copyleft/lgpl.html)
 * For more information about the class and upcoming tools and toys using it,
 * visit hhttp://phpYahoo.gotfoo.org or http://code.google.com/p/phpyahoo/
 *
 *     For installation instructions, open the README.txt file packaged with this
 *     class. If you don't have a copy, you can see it at:
 *     http://phpYahoo.gotfoo.org/README.txt
 *
 *     Please submit all issues to the project page:
 *         http://code.google.com/p/phpyahoo/issues/list
 * 
 
 */
if (session_id() == "") {
    session_start();
}

// Decides which include path delimiter to use.  Windows should be using a semi-colon
// and everything else should be using a colon.  If this isn't working on your system,
// comment out this if statement and manually set the correct value into $path_delimiter.
if (strpos(__FILE__, ':') !== false) {
    $path_delimiter = ';';
} else {
    $path_delimiter = ':';
}

// This will add the packaged PEAR files into the include path for PHP, allowing you
// to use them transparently.  This will prefer officially installed PEAR files if you
// have them.  If you want to prefer the packaged files (there shouldn't be any reason
// to), swap the two elements around the $path_delimiter variable.  If you don't have
// the PEAR packages installed, you can leave this like it is and move on.

ini_set('include_path', ini_get('include_path') . $path_delimiter . dirname(__FILE__) . '/PEAR');

// If you have problems including the default PEAR install (like if your open_basedir
// setting doesn't allow you to include files outside of your web root), comment out
// the line above and uncomment the next line:

// ini_set('include_path', dirname(__FILE__) . '/PEAR' . $path_delimiter . ini_get('include_path'));

class phpYahoo {
	
	var $appid = '';
	var $base_url = 'http://search.yahooapis.com/';
	var $command_web_search = 'WebSearchService/V1/webSearch';
	var $command_video_search = 'VideoSearchService/V1/videoSearch';
	var $command_related_search = 'WebSearchService/V1/relatedSuggestion';
	var $command_image_search = 'ImageSearchService/V1/imageSearch';
	var $max_cache_rows = 1000;  // 
	var $req;
	var $response;
    var $parsed_response;
    var $cache = false;
    var $cache_db = null;
    var $cache_table = null;
    var $cache_dir = null;
    var $cache_expire = null;
    var $die_on_error;
    var $error_code;
    Var $error_msg;
	
	function phpYahoo($appid){
		$this->appid = $appid;	
		
		//All calls to the API are done via the POST method using the PEAR::HTTP_Request package.
        require_once 'HTTP/Request.php';
        $this->req =& new HTTP_Request();
        $this->req->setMethod(HTTP_REQUEST_METHOD_POST);
	}
	
	function enableCache($type, $connection, $cache_expire = 600, $table = 'yahoo_cache') 
    {
        // Turns on caching.  $type must be either "db" (for database caching) or "fs" (for filesystem).
        // When using db, $connection must be a PEAR::DB connection string. Example:
        //      "mysql://user:password@server/database"
        // If the $table, doesn't exist, it will attempt to create it.
        // When using file system, caching, the $connection is the folder that the web server has write
        // access to. Use absolute paths for best results.  Relative paths may have unexpected behavior 
        // when you include this.  They'll usually work, you'll just want to test them.
        if ($type == 'db') {
            require_once 'DB.php';
            $db =& DB::connect($connection);
            if (PEAR::isError($db)) {
                die($db->getMessage());
            }
            
            /*
             * If high performance is crucial, you can easily comment
             * out this query once you've created your database table.
             */
             
            $db->query("
                CREATE TABLE IF NOT EXISTS `$table` (
                    `request` CHAR( 35 ) NOT NULL ,
                    `response` MEDIUMTEXT NOT NULL ,
                    `expiration` DATETIME NOT NULL ,
                    INDEX ( `request` )
                ) TYPE = MYISAM");
            
            if ($db->getOne("SELECT COUNT(*) FROM $table") > $this->max_cache_rows) {
                $db->query("DELETE FROM $table WHERE expiration < DATE_SUB(NOW(), INTERVAL $cache_expire second)");
                $db->query('OPTIMIZE TABLE ' . $this->cache_table);
            }

            $this->cache = 'db';
            $this->cache_db = $db;
            $this->cache_table = $table;
        } elseif ($type == 'fs') {
            $this->cache = 'fs';
            $connection = realpath($connection);
            $this->cache_dir = $connection;
            if ($dir = opendir($this->cache_dir)) {
                while ($file = readdir($dir)) {
                    if (substr($file, -6) == '.cache' && ((filemtime($this->cache_dir . '/' . $file) + $cache_expire) < time()) ) {
                        unlink($this->cache_dir . '/' . $file);
                    }
                }
            }
        }
        $this->cache_expire = $cache_expire;
    }
    
    function getCached ($request) 
    {
        //Checks the database or filesystem for a cached result to the request.
        //If there is no cache result, it returns a value of false. If it finds one,
        //it returns the unparsed XML.
        $reqhash = md5(serialize($request));
        if ($this->cache == 'db') {
            $result = $this->cache_db->getOne("SELECT response FROM " . $this->cache_table . " WHERE request = ? AND DATE_SUB(NOW(), INTERVAL " . (int) $this->cache_expire . " SECOND) < expiration", $reqhash);
            if (!empty($result)) {
                return $result;
            }
        } elseif ($this->cache == 'fs') {
            $file = $this->cache_dir . '/' . $reqhash . '.cache';
            if (file_exists($file)) {
				if ($this->php_version[0] > 4 || ($this->php_version[0] == 4 && $this->php_version[1] >= 3)) {
					return file_get_contents($file);
				} else {
					return implode('', file($file));
				}
            }
        }
        return false;
    }
    
    function cache ($request, $response) 
    {
        //Caches the unparsed XML of a request.
        $reqhash = md5(serialize($request));
        if ($this->cache == 'db') {
            //$this->cache_db->query("DELETE FROM $this->cache_table WHERE request = '$reqhash'");
            if ($this->cache_db->getOne("SELECT COUNT(*) FROM {$this->cache_table} WHERE request = '$reqhash'")) {
                $sql = "UPDATE " . $this->cache_table . " SET response = ?, expiration = ? WHERE request = ?";
                $this->cache_db->query($sql, array($response, strftime("%Y-%m-%d %H:%M:%S"), $reqhash));
            } else {
                $sql = "INSERT INTO " . $this->cache_table . " (request, response, expiration) VALUES ('$reqhash', '" . str_replace("'", "''", $response) . "', '" . strftime("%Y-%m-%d %H:%M:%S") . "')";
                $this->cache_db->query($sql);
            }
        } elseif ($this->cache == "fs") {
            $file = $this->cache_dir . "/" . $reqhash . ".cache";
            $fstream = fopen($file, "w");
            $result = fwrite($fstream,$response);
            fclose($fstream);
            return $result;
        }
        return false;
    }
    
   
    
    function clean_text_nodes($arr) {
        if (!is_array($arr)) {
            return $arr;
        } elseif (count($arr) == 0) {
            return $arr;
        } elseif (count($arr) == 1 && array_key_exists('_content', $arr)) {
            return $arr['_content'];
        } else {
            foreach ($arr as $key => $element) {
                $arr[$key] = $this->clean_text_nodes($element);
            }
            return($arr);
        }
    }
	
	
	
	function request($command,$params) 
    {     	    	    
	    $queryString = $this->createQueryString($params);
	    $url  = $this->base_url.$command.'?'.$queryString.'&appid='.$this->appid;
	    
	    $response = $this->getCached($url);
	    $strCache = "From Cache";
	    if($response == null){
	   		//echo $url;
			$c = curl_init($url);
			curl_setopt($c,CURLOPT_RETURNTRANSFER,true);
			$response = curl_exec($c);
			curl_close($c);		
			$this->cache($url,$response);
			$strCache = "From Yahoo";
				
		}
		$responseData = simplexml_load_string($response); 	
		
		echo $strCache;
		//print_r($responseData);
		return $responseData;
    }
    
    function resultSet_info($xml){
	   
	    $results = $xml->xpath('/ResultSet');
	    //print_r($resultSet);
	    $totalResultsAvailable = $xml[0]['totalResultsAvailable'];
	    $totalResultsReturned = $xml[0]['totalResultsReturned'];
	    $firstResultPosition = $xml[0]['firstResultPosition'];
	    $resultSet =  array("totalResultsAvailable"=>$totalResultsAvailable,"totalResultsReturned"=>$totalResultsReturned,"firstResultPosition"=>$firstResultPosition);
	    return $resultSet;
	    
    }
    
    function request_web_search ($params)     {   
	    $xml = $this->request($this->command_web_search,$params);	
	    $results = array();
		$i = 0;
	    //print_r($xml);
		//$resultSet = null;//$this->resultSet_info($xml);
		
		foreach($xml->Result as $result){			
			$tUnixTime = $result->ModificationDate;
			//$dspDate = date(DATE_W3C,);
			
			$fUTCOffset = -5.00; // GMT/UTC Offset in Hours (2.50 = 2 hours 30 minutes)
			$dspDate =  gmdate("Y-m-d H:i:s", $tUnixTime + $fUTCOffset * 3600);
			
			$results[$i] = array("title"=>$result->Title,"summary"=>$result->Summary,"url"=>$result->Url,"clickUrl"=>$result->ClickUrl,"displayUrl"=>$result->DisplayUrl,"modificationDate"=>$dspDate,"mimeType"=>$result->MimeType);
			$i++;				
		}		
		
		//return array("resultSet"=>$resultSet,"results"=>$results);
		return $results;
    }
    
      function request_related_search ($params)     {   
	    $xml = $this->request($this->command_related_search,$params);	    
		$results = array();
		$i = 0;
		foreach($xml as $result){			
			$results[$i] = array("result"=>$result->Result);
			$i++;				
		}
		return $results;
    }
    
	function request_video_search ($params)     {   
	    $xml = $this->request($this->command_video_search,$params);	    
		$results = array();
		$i = 0;
		foreach($xml->Result as $result){			
			$results[$i] = array("title"=>$result->Title,"summary"=>$result->Summary,"url"=>$result->Url,"clickUrl"=>$result->ClickUrl,"refererUrl"=>$result->RefererUrl,"fileSize"=>$result->FileSize,"fileFormat"=>$result->FileFormat,"weight"=>$result->Height,"width"=>$result->Width,"duration"=>$result->Duration,"streaming"=>$result->Streaming,"thumbnail"=>$result->Thumbnail->Url,"theight"=>$result->Thumbnail->Height,"twidth"=>$result->Thumbnail->Width);
			$i++;				
		}	
		
		return $results;
    } 
    
    function request_image_search ($params)     {   
	    $xml = $this->request($this->command_image_search,$params);	    
		$results = array();
		$i = 0;
		foreach($xml->Result as $result){			
			$results[$i] = array("title"=>$result->Title,"summary"=>$result->Summary,"url"=>$result->Url,"clickUrl"=>$result->ClickUrl,"refererUrl"=>$result->RefererUrl,"fileSize"=>$result->FileSize,"fileFormat"=>$result->FileFormat,"weight"=>$result->Height,"width"=>$result->Width,"thumbnail"=>$result->Thumbnail->Url,"theight"=>$result->Thumbnail->Height,"twidth"=>$result->Thumbnail->Width);
			$i++;				
		}	
		
		return $results;
    } 


    
    function createQueryString($query){	    
	    if (is_array($query)) {
            $queryString = http_build_query($query);             
        }else{      
	        $query = urlencode($query);  
        	$queryString = "query=$query&";
   		}   		
       	       	
       	return $queryString;
    }
    
    function searchWeb($params){
		//http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=madonna&results=2   		       
				
   		$response =  $this->request_web_search($params);//$this->createQueryString($query,$params));
       	return $response;
    }
    
    
    
    function searchRelated($query,$results=null){
		//http://search.yahooapis.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=madonna&results=2   		        
   		$response =  $this->request_related_search($this->createQueryString($query,$results));
       	return $response;
    }
    
    
    
	function searchVideos($query){
		//http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=madonna&results=2   		
		
      	$response =  $this->request_video_search($this->createQueryString($query,$results));       
       	return $response;
    }
    
    function searchImages($query){
		//http://search.yahooapis.com/VideoSearchService/V1/videoSearch?appid=YahooDemo&query=madonna&results=2   		
		
      	$response =  $this->request_image_search($this->createQueryString($query,$results));       
       	return $response;
    }
}

?>